/**
 * 用户信息，用户注册，用户信息修改路由
 */

var router = require('express').Router();
var userTool = require('../bin/user');
var assertAlljs = require('../bin/util/assert-alljs');
var ObjectID = require('mongodb').ObjectID;
var dbentityTool = require('../bin/dbentity');

router.get('/register.html', async function(req, res){
    var local = userTool.toLocal({});
    local.edit = true;
    local.register = true;
    local.isAdmin = false;
    res.render('dyn.useredit.html', local);
});

router.get('/useredit.html', async function(req, res) {
    let user = req.session.user;
    let assert = assertAlljs(req, res);
    if (await assert(userTool.check(user)))
        return;

    var local = userTool.toLocal(user);
    local.edit = true;
    local.register = false;
    local.isAdmin = false;
    res.render('dyn.useredit.html', local);
});

router.get('/userinfo.html', async function(req, res) {
    let user = req.session.user;
    let assert = assertAlljs(req, res);
    if (await assert(userTool.check(user)))
        return;

    var local = userTool.toLocal(user);
    local.edit = false;
    local.register = false;
    local.isAdmin = false;
    res.render('dyn.useredit.html', local);
});

router.get('/user', async function(req, res) {
    let user = req.session.user;
    let assert = assertAlljs(req, res);
    if (await assert(userTool.check(user, {role:'admin'})))
        return;

    if (await assert(typeof(req.query.id) !== 'string' || req.query.id === '', '缺少请求参数'))
        return;

    let result = await dbentityTool.findOne('user', { _id : ObjectID(req.query.id) });
    if (await assert(result instanceof Error, '查询数据库错误'))
        return;

    var local = userTool.toLocal(result);
    local.edit = false;
    local.register = false;
    local.isAdmin = true;
    res.render('dyn.useredit.html', local);
});

module.exports = router;